//! 错误处理模块
//! 
//! 定义了CDB数据库中所有可能的错误类型

use std::fmt;
use thiserror::Error;

/// CDB数据库错误类型
#[derive(Error, Debug)]
pub enum Error {
    /// SQL解析错误
    #[error("SQL解析错误: {0}")]
    SqlParse(#[from] sqlparser::parser::ParserError),
    
    /// 查询执行错误
    #[error("查询执行错误: {0}")]
    QueryExecution(String),
    
    /// 存储引擎错误
    #[error("存储引擎错误: {0}")]
    Storage(String),
    
    /// 事务错误
    #[error("事务错误: {0}")]
    Transaction(String),
    
    /// 网络协议错误
    #[error("网络协议错误: {0}")]
    Protocol(String),

    /// 网络错误
    #[error("网络错误: {0}")]
    Network(String),
    
    /// 配置错误
    #[error("配置错误: {0}")]
    Config(String),
    
    /// I/O错误
    #[error("I/O错误: {0}")]
    Io(#[from] std::io::Error),
    
    /// 序列化错误
    #[error("序列化错误: {0}")]
    Serialization(#[from] serde_json::Error),
    
    /// 数据类型错误
    #[error("数据类型错误: {0}")]
    DataType(String),
    
    /// 索引错误
    #[error("索引错误: {0}")]
    Index(String),
    
    /// 内存不足错误
    #[error("内存不足")]
    OutOfMemory,
    
    /// 连接错误
    #[error("连接错误: {0}")]
    Connection(String),
    
    /// 超时错误
    #[error("操作超时")]
    Timeout,
    
    /// 权限错误
    #[error("权限不足: {0}")]
    Permission(String),
    
    /// 数据库不存在
    #[error("数据库不存在: {0}")]
    DatabaseNotFound(String),
    
    /// 表不存在
    #[error("表不存在: {0}")]
    TableNotFound(String),
    
    /// 列不存在
    #[error("列不存在: {0}")]
    ColumnNotFound(String),
    
    /// 约束违反
    #[error("约束违反: {0}")]
    ConstraintViolation(String),
    
    /// 死锁检测
    #[error("检测到死锁")]
    Deadlock,
    
    /// 内部错误
    #[error("内部错误: {0}")]
    Internal(String),
}

impl Error {
    /// 创建SQL解析错误
    pub fn sql_parse<S: Into<String>>(msg: S) -> Self {
        Error::QueryExecution(msg.into()) // 暂时映射到QueryExecution
    }

    /// 创建查询执行错误
    pub fn query_execution<S: Into<String>>(msg: S) -> Self {
        Error::QueryExecution(msg.into())
    }
    
    /// 创建存储引擎错误
    pub fn storage<S: Into<String>>(msg: S) -> Self {
        Error::Storage(msg.into())
    }
    
    /// 创建事务错误
    pub fn transaction<S: Into<String>>(msg: S) -> Self {
        Error::Transaction(msg.into())
    }

    pub fn network<S: Into<String>>(msg: S) -> Self {
        Error::Network(msg.into())
    }
    
    /// 创建协议错误
    pub fn protocol<S: Into<String>>(msg: S) -> Self {
        Error::Protocol(msg.into())
    }
    
    /// 创建配置错误
    pub fn config<S: Into<String>>(msg: S) -> Self {
        Error::Config(msg.into())
    }
    
    /// 创建数据类型错误
    pub fn data_type<S: Into<String>>(msg: S) -> Self {
        Error::DataType(msg.into())
    }
    
    /// 创建索引错误
    pub fn index<S: Into<String>>(msg: S) -> Self {
        Error::Index(msg.into())
    }
    
    /// 创建连接错误
    pub fn connection<S: Into<String>>(msg: S) -> Self {
        Error::Connection(msg.into())
    }
    
    /// 创建权限错误
    pub fn permission<S: Into<String>>(msg: S) -> Self {
        Error::Permission(msg.into())
    }
    
    /// 创建约束违反错误
    pub fn constraint_violation<S: Into<String>>(msg: S) -> Self {
        Error::ConstraintViolation(msg.into())
    }
    
    /// 创建内部错误
    pub fn internal<S: Into<String>>(msg: S) -> Self {
        Error::Internal(msg.into())
    }
    
    /// 检查是否为可重试错误
    pub fn is_retryable(&self) -> bool {
        matches!(self, Error::Timeout | Error::Deadlock | Error::OutOfMemory)
    }
    
    /// 检查是否为致命错误
    pub fn is_fatal(&self) -> bool {
        matches!(self, Error::Internal(_) | Error::OutOfMemory)
    }
}

/// CDB数据库结果类型
pub type Result<T> = std::result::Result<T, Error>;

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_error_creation() {
        let err = Error::query_execution("测试错误");
        assert!(matches!(err, Error::QueryExecution(_)));
        assert_eq!(err.to_string(), "查询执行错误: 测试错误");
    }
    
    #[test]
    fn test_error_properties() {
        let timeout_err = Error::Timeout;
        assert!(timeout_err.is_retryable());
        assert!(!timeout_err.is_fatal());
        
        let internal_err = Error::internal("内部错误");
        assert!(!internal_err.is_retryable());
        assert!(internal_err.is_fatal());
    }
    
    #[test]
    fn test_error_display() {
        let err = Error::TableNotFound("users".to_string());
        assert_eq!(err.to_string(), "表不存在: users");
    }
}
